<!-- Created by henian.xu on 2018/9/11. -->

<template>
    <div class="tinymce-image-upload">
        <el-button
            icon="el-icon-upload"
            size="mini"
            type="primary"
            @click=" dialogVisible=true">上传图片
        </el-button>
        <el-dialog :visible.sync="dialogVisible">
            <upload
                ref="upload"
                :action="action"
                accept="image/*"
                :limit="2"
                return-files
                :before-upload="beforeUpload"
                v-model="upload"
            />

            <div
                slot="footer"
                class="dialog-footer">
                <el-button
                    type="primary"
                    size="small"
                    @click="onAddDialogConfirm"
                >确 定
                </el-button>
                <el-button
                    size="small"
                    @click="onAddDialogCancel"
                >取 消
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'ImageUpload',
    data() {
        return {
            dialogVisible: false,
            upload: [],
        };
    },
    props: {
        action: {
            type: String,
            default: '',
        },
    },
    methods: {
        beforeUpload(file) {
            const _URL = window.URL || window.webkitURL;
            const fileUrl = _URL.createObjectURL(file);
            console.log(fileUrl);
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => {
                    file.width = img.width;
                    file.height = img.height;
                    resolve(true);
                };
                img.onerror = () => {
                    reject(false);
                };
                img.src = fileUrl;
            });
        },
        onAddDialogConfirm() {
            if (!this.$refs.upload.isComplete) {
                this.$message('请等待所有图片上传成功 或 出现了网络问题，请刷新页面重新上传！');
                return;
            }
            const files = this.upload.reduce((prev, curr) => {
                prev.push({
                    src: curr.address,
                    width: curr.raw.width,
                    height: curr.raw.height,
                });
                return prev;
            }, []);
            console.log(files);
            // files.push('//www.tinymce.com/images/glyph-tinymce@2x.png');
            this.$emit('successCBK', files);
            this.$refs.upload.clear();
            this.dialogVisible = false;
        },
        onAddDialogCancel() {
            this.$refs.upload.clear();
            this.dialogVisible = false;
        },
    },
};
</script>

<style lang="scss">
.tinymce-image-upload {
    display: inline-block;
}
</style>
